package com.oscar.ehome.view.pageview;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.oscar.ehome.R;
import com.oscar.ehome.base.C;
import com.oscar.ehome.base.activity.BasesActivity;
import com.oscar.ehome.base.view.DragGridView;
import com.oscar.ehome.bean.UsersBean;
import com.oscar.ehome.bean.loginbean.UserBean;
import com.oscar.ehome.bean.setbean.SetMessageBean;
import com.oscar.ehome.presenter.PagePresenter;
import com.oscar.ehome.utils.system.SystemConfigFactory;
import com.oscar.ehome.utils.util.AesUtils;
import com.oscar.ehome.utils.util.CommonUtils;
import com.oscar.ehome.utils.util.ToastUtil;
import com.oscar.ehome.utils.util.makeTime;
import com.oscar.ehome.view.loginview.LoginActivity;
import com.oscar.ehome.view.pageview.adapter.AddGridViewAdapter;
import com.oscar.ehome.view.pageview.adapter.DeleteGridAdapter;
import com.oscar.ehome.view.pageview.view.DuDaoXiangQingView;
import com.oscar.ehome.view.pageview.view.SaveAppListView;
import com.oscar.ehome.view.setview.SigninActivity;
import com.oscar.ehome.view.teamview.TeamCountViewActivity;
import com.umeng.analytics.MobclickAgent;

import net.tycmc.bulb.androidstandard.utils.JsonUtils;

import org.apache.commons.collections.MapUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by oscar
 * author: MengWanhe
 * date: On 2017/6/28
 * 应用编辑页面
 */

public class ApplationsActivity extends BasesActivity<SaveAppListView, PagePresenter> implements AddGridViewAdapter.OnClickslister, DeleteGridAdapter.DeleteClicklister,
        SaveAppListView, AdapterView.OnItemClickListener {

    /**
     * 返回
     */
    @BindView(R.id.title_img_back)
    ImageView titleImgBack;
    /**
     * 返回
     */
    @BindView(R.id.title_layout_left)
    RelativeLayout titleLayoutLeft;
    /**
     * 编辑
     */
    @BindView(R.id.home_tv_num)
    TextView homeTvNum;

    @BindView(R.id.right_layout)
    RelativeLayout rightLayout;
    /**
     * 标题
     */
    @BindView(R.id.title_topbar)
    TextView titleTopbar;
    /**
     * 添加view
     */
    @BindView(R.id.add_dragGridView)
    GridView addDragGridView;
    /**
     * 删除view
     */
    @BindView(R.id.delete_dragGridView)
    DragGridView deleteDragGridView;
    /**
     * title布局
     */
    @BindView(R.id.basetitle_bar)
    RelativeLayout basetitleBar;

    @BindView(R.id.applation_views)
    View applationViews;
    @BindView(R.id.applation_view)
    View applationView;

    //添加adapter
    AddGridViewAdapter addAdapter;
    //删除adapter
    DeleteGridAdapter deleteAdapter;
    //列数
    int colnum = 4;
    //长度
    int size = 0;
    //是否编辑
    int compile = 0;

    //删除的应用数据
    List<String> delete_list = new ArrayList<>();
    Map<String, Object> delete_map = new HashMap<String, Object>();

    //添加的应用数据
    List<String> add_list = new ArrayList<>();
    Map<String, Object> add_map = new HashMap<String, Object>();
    //总数据
    List<String> list = new ArrayList<>();
    Map<String, Object> map = new HashMap<String, Object>();

    PagePresenter pagePresenter;
    String token = "",people="",touxiang="";
    UsersBean userBe;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_applation);
        ButterKnife.bind(this);
        setColor();
        initView();
        initSetData();
        inintDelete();
        inintAdd();
    }

    @Override
    protected PagePresenter createPresenter() {
        pagePresenter = new PagePresenter(this);
        return pagePresenter;
    }

    /**
     * 设置颜色
     */
    public void setColor() {
        basetitleBar.setBackgroundColor(Color.parseColor(SystemConfigFactory.getInstance(ApplationsActivity.this).getSystemConfig().getColor()));
        applationViews.setBackgroundColor(Color.parseColor(SystemConfigFactory.getInstance(ApplationsActivity.this).getSystemConfig().getColor()));
        applationView.setBackgroundColor(Color.parseColor(SystemConfigFactory.getInstance(ApplationsActivity.this).getSystemConfig().getColor()));

        String message = SystemConfigFactory.getInstance(ApplationsActivity.this).getSystemConfig().getUserMessage();
        if (message != null && !"".equals(message)) {
            userBe = new Gson().fromJson(message, UsersBean.class);
        }
    }

    @OnClick({R.id.right_layout, R.id.title_layout_left})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.right_layout://编辑
                if (compile == 0) {
                    compile = 1;
                    CommonUtils.isPress = 1;
                    updateAdapter(1);
                    homeTvNum.setText(getString(R.string.oks));
                } else {
                    save();
                    CommonUtils.isPress = 0;
                    compile = 0;
                    updateAdapter(0);
                    homeTvNum.setText(getString(R.string.bianji));
                }
                break;
            case R.id.title_layout_left://返回
                finish();
                break;
        }
    }

    /**
     * 加载数据
     */
    public void initView() {
        homeTvNum.setText(getString(R.string.bianji));
        rightLayout.setVisibility(View.VISIBLE);
        homeTvNum.setVisibility(View.VISIBLE);
        titleImgBack.setImageResource(R.mipmap.fanhui);
        titleTopbar.setText(getString(R.string.menu));

        token = SystemConfigFactory.getInstance(ApplationsActivity.this).getSystemConfig().getToken();

        //计算列数
        size = colnum;

        deleteDragGridView.setOnItemClickListener(this);
        addDragGridView.setOnItemClickListener(this);
        if( SystemConfigFactory.getInstance(ApplationsActivity.this).getSystemConfig().getyaoqing()!=null&&
                !SystemConfigFactory.getInstance(ApplationsActivity.this).getSystemConfig().getyaoqing().equals("false")&&
                !SystemConfigFactory.getInstance(ApplationsActivity.this).getSystemConfig().getyaoqing().equals("")){
            Intent intents=getIntent();
            people= intents.getStringExtra("people");
            touxiang=intents.getStringExtra("touxiang");
        }else{

        }
    }

    /**
     * 添加数据
     */
    public void initSetData() {
        String addlist = SystemConfigFactory.getInstance(ApplationsActivity.this).getSystemConfig().getAddapp();
        String deletelist = SystemConfigFactory.getInstance(ApplationsActivity.this).getSystemConfig().getDeleteapp();
        if (addlist != null && !"".equals(addlist)) {
            add_map = JsonUtils.fromJsonToHashMap(addlist);
            add_list = (List<String>) MapUtils.getObject(add_map, "addlist");

            if (add_list == null) {
                add_list.add("");
            }
        }
        if (deletelist != null && !"".equals(deletelist)) {
            delete_map = JsonUtils.fromJsonToHashMap(deletelist);
            delete_list = (List<String>) MapUtils.getObject(delete_map, "deletelist");
            if (delete_list == null) {
                delete_list.add("");
            }

        }
        if (delete_list.size() == 0 && add_list.size() == 0) {
            setAllData();
        }
    }

    /**
     * 添加全部数据
     */
    public void setAllData() {
        String applist = SystemConfigFactory.getInstance(ApplationsActivity.this).getSystemConfig().getAppaction();

        map = JsonUtils.fromJsonToHashMap(applist);

        list = (List<String>) MapUtils.getObject(map, "applist");
        if (list.size() > 4) {
            for (int i = 0; i < list.size(); i++) {
                if (i < 4) {
                    delete_list.add(list.get(i));//首页菜单数据
                } else {
                    add_list.add(list.get(i));//其他菜单数据
                }
            }
        } else {
            for (int i = 0; i < list.size(); i++) {
                add_list.add(list.get(i));
            }
        }
    }

    /**
     * 删除数据adapter
     */
    public void inintDelete() {
        deleteAdapter = new DeleteGridAdapter(ApplationsActivity.this, size, delete_list);
        deleteDragGridView.setAdapter(deleteAdapter);
        deleteAdapter.setDeleteClicksListener(this);
        size = delete_list.size();
    }

    /**
     * 添加数据adapter
     */
    public void inintAdd() {
        addAdapter = new AddGridViewAdapter(ApplationsActivity.this, add_list);
        addDragGridView.setAdapter(addAdapter);
        addAdapter.setOnClicksListener(this);
    }

    /**
     * 更新每个item的状态
     *
     * @param update
     */
    public void updateAdapter(int update) {
        deleteAdapter.setUpdate(update);
        addAdapter.setUpdate(update);
        if (update == 0) {
            save();
            Map<String, Object> map = new HashMap<String, Object>();
            List<String> all_list = new ArrayList<>();
            for (int i = 0; i < delete_list.size(); i++) {
                all_list.add(delete_list.get(i));
            }
            for (int i = 0; i < add_list.size(); i++) {
                all_list.add(add_list.get(i));
            }
            map.put("applist", all_list);
            String addapp = JsonUtils.toJson(map);
            SystemConfigFactory.getInstance(ApplationsActivity.this).getSystemConfig().setAppactionnum(delete_list.size());
            SystemConfigFactory.getInstance(ApplationsActivity.this).getSystemConfig().setAppaction(addapp);
            pagePresenter.saveApp(token, CommonUtils.ListToString(all_list, 1));

        }
    }

    /**
     * 本地存储一份list
     */
    public void save() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("addlist", add_list);
        String addapp = JsonUtils.toJson(map);
        SystemConfigFactory.getInstance(ApplationsActivity.this).getSystemConfig().setAddapp(addapp);

        Map<String, Object> maps = new HashMap<String, Object>();
        maps.put("deletelist", delete_list);
        String deapp = JsonUtils.toJson(maps);
        SystemConfigFactory.getInstance(ApplationsActivity.this).getSystemConfig().setDeleteapp(deapp);

    }


    /**
     * 添加时
     */
    @Override
    public void OnClick(int postion) {
        if (size < 4) {
            String add = add_list.get(postion);
            delete_list.add(add);
            add_list.remove(postion);
            size = size + 1;
            deleteAdapter.setList(delete_list, size);
            addAdapter.setList(add_list);
//            save();
        } else {
            ToastUtil.show(ApplationsActivity.this, "首页最多选择四个菜单");
        }
    }

    /**
     * 删除时
     */
    @Override
    public void DeleteClick(int postion) {
        if (size > 0) {
            String delete = delete_list.get(postion);
            add_list.add(delete);
            delete_list.remove(postion);

            size = size - 1;
            deleteAdapter.setList(delete_list, size);
            addAdapter.setList(add_list);
//            save();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (compile == 1) {
                compile = 0;
                updateAdapter(0);
                homeTvNum.setText(getString(R.string.bianji));
                return false;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void saveApp(String result) {
        ToastUtil.show(ApplationsActivity.this, result);
    }

    @Override
    public void erroy() {
        ToastUtil.show(ApplationsActivity.this, getString(R.string.erry));
    }

    @Override
    public void erry(String result) {
        if (result.contains("过期")) {
            getSharedPreferences("appbase", Context.MODE_PRIVATE).edit().clear().commit();
            SystemConfigFactory.getInstance(ApplationsActivity.this).getSystemConfig().SetLogin(false);
            SystemConfigFactory.getInstance(this).getSystemConfig().setIsFirst(true);
            Intent intent = new Intent(ApplationsActivity.this, LoginActivity.class);
            startActivity(intent);
            finish();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (parent == deleteDragGridView) {
            if (compile == 0) {
                initActivty(position, delete_list);
            }else{
                if (size > 0) {
                    String delete = delete_list.get(position);
                    add_list.add(delete);
                    delete_list.remove(position);

                    size = size - 1;
                    deleteAdapter.setList(delete_list, size);
                    addAdapter.setList(add_list);
//            save();
                }
            }
        }
        if (parent == addDragGridView) {
            if (compile == 0) {
                initActivty(position, add_list);
            }else{

                if (size < 4) {
                    String add = add_list.get(position);
                    delete_list.add(add);
                    add_list.remove(position);
                    size = size + 1;
                    deleteAdapter.setList(delete_list, size);
                    addAdapter.setList(add_list);
//            save();
                } else {
                    ToastUtil.show(ApplationsActivity.this, "首页最多选择四个菜单");
                }
            }
        }
    }

    public void initActivty(int postion, List<String> list) {
        String stats = list.get(postion);
        switch (stats) {
            case "8"://应用中心
                MobclickAgent.onEvent(this,"yingyongzhongxin");
                Intent intent = new Intent(ApplationsActivity.this, AppListActivity.class);
                startActivity(intent);
                break;
            case "7"://考勤签到
                MobclickAgent.onEvent(this,"kaoqinqiandao");
                if (userBe != null) {
                    if (userBe.getIsPay() != null&& "1".equals(userBe.getIsPay())) {
                                  startActivity(new Intent(ApplationsActivity.this, SigninActivity.class));

                    } else {
                        Toast.makeText(ApplationsActivity.this, "请支付后进入", Toast.LENGTH_SHORT).show();
                    }
                }

                break;
            case "6"://统计
                MobclickAgent.onEvent(this,"tongji");
                Intent intent_tj = new Intent(ApplationsActivity.this, TeamCountNewActivity.class);
                String user = SystemConfigFactory.getInstance(ApplationsActivity.this).getSystemConfig().getUserBean();
                UserBean userBean = new Gson().fromJson(user, UserBean.class);
                intent_tj.putExtra("member_name", userBean.getName());
                intent_tj.putExtra("id", SystemConfigFactory.getInstance(ApplationsActivity.this).getSystemConfig().getUuid());
                startActivity(intent_tj);
                break;
            case "9"://准会员
                MobclickAgent.onEvent(this,"zhunhuiyuan");
                Intent intent_member = new Intent(ApplationsActivity.this, MembersListActivity.class);
                startActivity(intent_member);
                break;
            case "4"://学习管理
                MobclickAgent.onEvent(this,"xuexi");
                Intent intent_study = new Intent(ApplationsActivity.this, Study_GuoDuActivity.class);
                startActivity(intent_study);
                break;
            case "3"://活动管理
                MobclickAgent.onEvent(this,"huodong");
                Intent intent_hd = new Intent(ApplationsActivity.this, HuoDongActivity.class);
                startActivity(intent_hd);
                break;
            case "11"://寿险通
                MobclickAgent.onEvent(this,"shouxiantong");
                Intent intent_sxt = new Intent(ApplationsActivity.this, BannerWebActivity.class);
                intent_sxt.putExtra("contentsrc", C.sxturl);
                intent_sxt.putExtra("type", "sxt");
                intent_sxt.putExtra("name", "");
                intent_sxt.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent_sxt);
                break;
            case "10"://掌中宝
                MobclickAgent.onEvent(this,"zhangzhongbao");
                Intent intent_zzb = new Intent(ApplationsActivity.this, BannerWebActivity.class);
                intent_zzb.putExtra("contentsrc", C.zzburl);
                intent_zzb.putExtra("type", "zzb");
                intent_zzb.putExtra("name", "");
                intent_zzb.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent_zzb);
                break;
            case "12"://拜访记录
                MobclickAgent.onEvent(this,"baoxiandangan");
                Intent intent_jl = new Intent(ApplationsActivity.this, InsuranceActivity.class);
                startActivity(intent_jl);
                break;
            case "13"://拜访记录
                MobclickAgent.onEvent(this,"gongzuorizhi");
                Intent intent_worklog = new Intent(ApplationsActivity.this, WorkListActivity.class);
                startActivity(intent_worklog);
                break;
            case "14"://长知识
                MobclickAgent.onEvent(this,"zhangzhishi");
                Intent intent_know = new Intent(ApplationsActivity.this, ClassroomActivity.class);
                startActivity(intent_know);
                break;
            case "15"://获客
                MobclickAgent.onEvent(this,"huoke");
                if (userBe != null) {
                    if (userBe.getIsPay() != null&& "1".equals(userBe.getIsPay())) {
                           Intent intent_huike = new Intent(ApplationsActivity.this, HuokeListActivity.class);
                            startActivity(intent_huike);

                    } else {
                        Toast.makeText(ApplationsActivity.this, "请支付后进入", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
            case "16"://考勤签到
                MobclickAgent.onEvent(this,"qiandao");
                if (userBe != null) {
                    Log.e("zhifujieguo", "initActivty: "+userBe.getIsPay() );
                    if (userBe.getIsPay() != null&& "1".equals(userBe.getIsPay())) {
                            startActivity(new Intent(ApplationsActivity.this, SigninTwoActivity.class));

                    } else {
                        Toast.makeText(ApplationsActivity.this, "请支付后进入", Toast.LENGTH_SHORT).show();
                    }
                }

                break;
            case "17"://督导
                MobclickAgent.onEvent(this,"dudao");
                if (userBe != null) {
                    startActivity(new Intent(ApplationsActivity.this, DuDaoLieBiao.class));

                }

                break;
            case "18"://dudao
                MobclickAgent.onEvent(this,"nimingjubao");
                if (userBe != null) {
                    startActivity(new Intent(ApplationsActivity.this, NimingjubaoActivity.class));
                }

                break;
            case "19"://dudao
                MobclickAgent.onEvent(this,"mingpian");
                if( SystemConfigFactory.getInstance(ApplationsActivity.this).getSystemConfig().getyaoqing()!=null&&
                        !SystemConfigFactory.getInstance(ApplationsActivity.this).getSystemConfig().getyaoqing().equals("false")&&
                        !SystemConfigFactory.getInstance(ApplationsActivity.this).getSystemConfig().getyaoqing().equals("")){


                    Intent in=new Intent();
                    in.putExtra("contentsrc",SystemConfigFactory.getInstance(ApplationsActivity.this).getSystemConfig().getyaoqing());
                    in.putExtra("type","yaoqing");
                    in.putExtra("people", people);
                    in.putExtra("touxiang", touxiang);
                    in.putExtra("name","名片");
                    in.setClass(ApplationsActivity.this,BannerWebActivity.class);
                    startActivity(in);
                }else{
                    startActivity(new Intent(ApplationsActivity.this, MingPianActivity.class));
                }

                break;
            case "20"://dudao
                MobclickAgent.onEvent(this,"youxi");
                try {
                    String mtime = makeTime.mtime();
                    String aes = AesUtils.encryptAES(mtime, "1234567812345678");

                    String url=C.ip+C.port+"/app/recreation/recreation/loadRecreation?timestamp="+aes+"&token="+token;
                    Intent youxi = new Intent(ApplationsActivity.this, BannerWebActivity.class);
                    youxi.putExtra("contentsrc", url);
                    youxi.putExtra("name", "游戏");
                    youxi.putExtra("type", "youxi");
                    youxi.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(youxi);
                }catch (Exception e){

                }


                break;
            case "21"://baodan
                MobclickAgent.onEvent(ApplationsActivity.this, "baodantuoguan");
                Intent in = new Intent();
                in.setClass(ApplationsActivity.this, BaoDanKeHuList.class);
                startActivity(in);

                break;
            case "22"://yejichaxun
                MobclickAgent.onEvent(ApplationsActivity.this, "yejichaxun");
                Intent in_yeji = new Intent();
                in_yeji.setClass(ApplationsActivity.this, YeJiChaXunList.class);
                startActivity(in_yeji);

                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }
    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }
}
